//
//  NYLoginViewController.m
//  Nooryes
//
//  Created by baken on 2020/2/26.
//  Copyright © 2020 MyApp. All rights reserved.
//

#import "NYLoginViewController.h"
#import "NYLoginViewModel.h"
#import "NYAlertView.h"
#import "MBProgressHUD.h"
#import "AccountModel.h"
#import "WebViewController.h"


@interface NYLoginViewController ()<UITextFieldDelegate>

@property (nonatomic, strong) NSTimer *countDownTimer;

@property (nonatomic, strong) NYLoginViewModel *loginVM;

@property (nonatomic, assign) int secondCount;

@property (weak, nonatomic) IBOutlet UITextField *registerPhone;
@property (weak, nonatomic) IBOutlet UITextField *loginPhone;

@property (weak, nonatomic) IBOutlet UIView *middleView;
@property (strong, nonatomic) IBOutlet UIView *loginView;
@property (strong, nonatomic) IBOutlet UIView *registerView;
@property (weak, nonatomic) IBOutlet UIButton *verifyButton;
@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;
@property (weak, nonatomic) IBOutlet UITextField *codeTextField;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *middleLeft;
@property (weak, nonatomic) IBOutlet UIView *hiddenView;

@end

@implementation NYLoginViewController

-(NYLoginViewModel *)loginVM{
    if (!_loginVM) {
        _loginVM = [NYLoginViewModel new];
    }
    return _loginVM;
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.countDownTimer invalidate];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyBoard)];
    [self.view addGestureRecognizer:tapGesture];
    
    [self.middleView addSubview:self.loginView];
    [self.middleView addSubview:self.registerView];
    
    if (myDelegate.isDisplay) {
        self.hiddenView.hidden = NO;
    } else{
        self.hiddenView.hidden = YES;
    }

}


-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    self.registerView.frame = CGRectMake(0, 0, self.middleView.frame.size.width *0.5, self.middleView.frame.size.height);
    self.loginView.frame = CGRectMake(self.middleView.frame.size.width *0.5, 0, self.middleView.frame.size.width *0.5, self.middleView.frame.size.height);
}


-(void)loginSuccess{
    NYAlertView *alert = [NYAlertView sharedAlertView];
    alert.title = @"登录成功";
    [alert showAlert:^{
        [self.middleView removeFromSuperview];
        if (IsNilOrNull(self.controller)) {
            [self.navigationController popToRootViewControllerAnimated:YES];
        } else {
            for (UIViewController *obj in [self.navigationController viewControllers]) {
                if ([obj isKindOfClass:[self.controller class]]) {
                    [self.navigationController popToViewController:obj animated:YES];
                    break ;
                }
            }
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
        
    }];
    //            [self showIdentify];
}

- (IBAction)qqLogin:(id)sender {
    //例如QQ的登录
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.loginVM.loginPlatform = @"1";
    [self.loginVM thrLoginWithCompletionHandle:^(NSError *error) {
        NYAlertView *alert = [NYAlertView sharedAlertView];
        if (error) {
            alert.title = [error.userInfo objectForKey:@"NSLocalizedDescription"]?[error.userInfo objectForKey:@"NSLocalizedDescription"]:@"登录失败";
            [alert showAlert:^{
            }];
        } else{
            [self loginSuccess];
        }
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
    }];
}

- (IBAction)wechatLogin:(id)sender {
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.loginVM.loginPlatform = @"2";
    [self.loginVM thrLoginWithCompletionHandle:^(NSError *error) {
        NYAlertView *alert = [NYAlertView sharedAlertView];
        if (error) {
            alert.title = [error.userInfo objectForKey:@"NSLocalizedDescription"]?[error.userInfo objectForKey:@"NSLocalizedDescription"]:@"登录失败";
        } else{
            [self loginSuccess];
        }
        [alert showAlert:^{
        }];
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
    }];
}

- (IBAction)displayPhoneLoginOrRegister:(id)sender {
    [self.middleLeft setConstant:self.middleLeft.constant==0?(-self.middleView.frame.size.width *0.5):0];
    [UIView animateWithDuration:0.3 animations:^{
        [self.view layoutIfNeeded];
    }];
}


- (IBAction)onPasswordLogin:(id)sender {
    NSString *regex = @"^[1][345678][0-9]{9}$";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isValid = [predicate evaluateWithObject:self.loginPhone.text];
    if (isValid) {
        self.loginVM.phoneNum = self.loginPhone.text;
        self.loginVM.password = self.passwordTextField.text;
        [self.loginVM phonePasswordLoginWithCompletionHandle:^(NSError *error) {
            if (!error) {
                [self loginSuccess];
            } else {
                NYAlertView *alert = [NYAlertView sharedAlertView];
                alert.title = [error.userInfo objectForKey:@"NSLocalizedDescription"];
                [alert showAlert:^{
                }];
            }
        }];
    }else {
        self.loginPhone.text = @"";
        NYAlertView *alert = [NYAlertView sharedAlertView];
        alert.title = @"请输入正确的手机号";
        [alert showAlert:^{}];
    }
    
}

- (IBAction)onPhoneCodeLogin:(id)sender {
    NSString *regex = @"^[1][345678][0-9]{9}$";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isValid = [predicate evaluateWithObject:self.registerPhone.text];
    if (isValid) {
        NSString *regex = @"^\\d{6}$";
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
        BOOL isValid = [predicate evaluateWithObject:self.codeTextField.text];
        if (isValid) {
            self.loginVM.code = self.codeTextField.text;
            self.loginVM.phoneNum = self.registerPhone.text;
            [self.loginVM phoneCodeLoginWithCompletionHandle:^(NSError *error) {
                if (!error) {
                    [self loginSuccess];
                } else {
                    NYAlertView *alert = [NYAlertView sharedAlertView];
                    alert.title = [error.userInfo objectForKey:@"NSLocalizedDescription"];
                    [alert showAlert:^{}];
                }
            }];
        } else{
            NYAlertView *alert = [NYAlertView sharedAlertView];
            alert.title = @"请输入正确的验证码";
            [alert showAlert:^{}];
        }
    } else {
        self.loginPhone.text = @"";
        NYAlertView *alert = [NYAlertView sharedAlertView];
        alert.title = @"请输入正确的手机号";
        [alert showAlert:^{}];
    }
    
}
- (IBAction)onSettlement:(id)sender {
    
    WebViewController *webVC = [[WebViewController alloc] init];
    webVC.urlString = @"http://m.onesavour.cn/static/down/fw.html";
    [self.navigationController pushViewController:webVC animated:YES];
}

- (IBAction)getVerifyCode:(id)sender {
    NSString *regex = @"^[1][345678][0-9]{9}$";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isValid = [predicate evaluateWithObject:self.registerPhone.text];
    if (isValid) {
        self.loginVM.phoneNum = self.registerPhone.text;
        self.loginVM.verifyType = @"2";
        [self.loginVM getVerifyCodeWithCompletionHandle:^(NSError *error) {
            if (!error) {
                self.verifyButton.userInteractionEnabled = NO;
                self.verifyButton.backgroundColor = UIColorFromRGB(0xe3e3e3);
                [self.verifyButton setTitleColor: UIColorFromRGB(0x999999) forState:UIControlStateNormal];
                self.secondCount = 60;
                self.countDownTimer =[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countDown) userInfo:nil repeats:YES];
                self.codeTextField.text = self.loginVM.code;
            } else {
                NYAlertView *alert = [NYAlertView sharedAlertView];
                alert.title = [error.userInfo objectForKey:@"NSLocalizedDescription"];
                [alert showAlert:^{
                    //                if (self.loginVM.u9Account.error_code == 4104) {
                    //                    for (UIViewController *vc in self.navigationController.childViewControllers) {
                    //                        if ([vc isKindOfClass:[LoginViewController class]]) {
                    //                            [self.navigationController popToViewController:vc animated:YES];
                    //                        }
                    //                    }
                    //                }
                    
                }];
            }
        }];
    }  else {
        self.registerPhone.text = @"";
        NYAlertView *alert = [NYAlertView sharedAlertView];
        alert.title = @"请输入正确的手机号";
        [alert showAlert:^{}];
    }
    
}

- (void)countDown{
    _secondCount--;
    if(_secondCount==0){
        self.verifyButton.userInteractionEnabled = YES;
        self.verifyButton.titleLabel.text = @"获取验证码";
        [self.verifyButton setTitle:@"获取验证码" forState:UIControlStateNormal];
        [_countDownTimer invalidate];
    } else {
        self.verifyButton.titleLabel.text = [NSString stringWithFormat:@"%iS后重新获取",_secondCount];
        [self.verifyButton setTitle:[NSString stringWithFormat:@"%iS后重新获取",_secondCount] forState:UIControlStateNormal];
    }
}
- (void)hideKeyBoard{
    [self.registerPhone resignFirstResponder];
    [self.codeTextField resignFirstResponder];
    [self.passwordTextField resignFirstResponder];
    [self.loginPhone resignFirstResponder];
    
}

- (void)showIdentify{
    //    if (!self.loginVM.account.namestatus) {
    //        U9IdentifyUserViewController *identifyVC = [[U9IdentifyUserViewController alloc] initWithNibName:@"U9IdentifyUserViewController" bundle:nil];
    //        self.definesPresentationContext = YES;
    //        identifyVC.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    //        identifyVC.block = ^(BOOL b){
    //            [self.navigationController popViewControllerAnimated:YES];
    //        };
    //        [self.navigationController presentViewController:identifyVC animated:YES completion:nil];
    //    } else {
    //        [self.navigationController popViewControllerAnimated:YES];
    //    }
    
    
}

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if ([textField isEqual:self.registerPhone]) {
        if (range.location +string.length ==11) {
            self.verifyButton.enabled = YES;
            self.verifyButton.backgroundColor = UIColorFromRGB(0xff3030);
            [self.verifyButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        } else {
            self.verifyButton.backgroundColor = UIColorFromRGB(0xe3e3e3);
            [self.verifyButton setTitleColor: UIColorFromRGB(0x999999) forState:UIControlStateNormal];
        }
        
    }
    
    return YES;
}
- (IBAction)backToRecommendVC:(id)sender {
    self.tabBarController.selectedIndex = 0;
    [self.navigationController popViewControllerAnimated:NO];
    
}


@end
